import { ref, reactive, computed, watch, type Ref, type ComputedRef } from 'vue'
import { ElMessage } from 'element-plus'

// 全局状态接口定义
interface GlobalState {
  // 应用状态
  app: {
    loading: boolean
    theme: 'light' | 'dark'
    language: 'zh' | 'en'
    sidebarCollapsed: boolean
    pageTitle: string
  }
  
  // 用户状态
  user: {
    isLoggedIn: boolean
    userInfo: any | null
    permissions: string[]
    preferences: Record<string, any>
  }
  
  // 测试状态
  quiz: {
    currentCategory: string | null
    currentQuestionIndex: number
    answers: Record<string, any>
    timeRemaining: number
    isSubmitting: boolean
  }
  
  // 缓存状态
  cache: {
    questions: Record<string, any[]>
    results: Record<string, any>
    stats: Record<string, any>
  }
}

// 创建全局状态
const globalState = reactive<GlobalState>({
  app: {
    loading: false,
    theme: 'light',
    language: 'zh',
    sidebarCollapsed: false,
    pageTitle: '心理测评系统'
  },
  
  user: {
    isLoggedIn: false,
    userInfo: null,
    permissions: [],
    preferences: {}
  },
  
  quiz: {
    currentCategory: null,
    currentQuestionIndex: 0,
    answers: {},
    timeRemaining: 0,
    isSubmitting: false
  },
  
  cache: {
    questions: {},
    results: {},
    stats: {}
  }
})

// 状态持久化配置
const STORAGE_KEY = 'app_global_state'
const PERSIST_KEYS = ['app.theme', 'app.language', 'user.preferences']

// 全局状态管理 Composable
export const useStore = () => {
  
  // 获取状态
  const getState = () => globalState
  
  // 应用状态管理
  const useAppState = () => {
    const setLoading = (loading: boolean) => {
      globalState.app.loading = loading
    }
    
    const setTheme = (theme: 'light' | 'dark') => {
      globalState.app.theme = theme
      document.documentElement.setAttribute('data-theme', theme)
      persistState()
    }
    
    const setLanguage = (language: 'zh' | 'en') => {
      globalState.app.language = language
      persistState()
    }
    
    const toggleSidebar = () => {
      globalState.app.sidebarCollapsed = !globalState.app.sidebarCollapsed
    }
    
    const setPageTitle = (title: string) => {
      globalState.app.pageTitle = title
      document.title = title
    }
    
    return {
      loading: computed(() => globalState.app.loading),
      theme: computed(() => globalState.app.theme),
      language: computed(() => globalState.app.language),
      sidebarCollapsed: computed(() => globalState.app.sidebarCollapsed),
      pageTitle: computed(() => globalState.app.pageTitle),
      setLoading,
      setTheme,
      setLanguage,
      toggleSidebar,
      setPageTitle
    }
  }
  
  // 用户状态管理
  const useUserState = () => {
    const setUserInfo = (userInfo: any) => {
      globalState.user.userInfo = userInfo
      globalState.user.isLoggedIn = !!userInfo
    }
    
    const setPermissions = (permissions: string[]) => {
      globalState.user.permissions = permissions
    }
    
    const setPreference = (key: string, value: any) => {
      globalState.user.preferences[key] = value
      persistState()
    }
    
    const getPreference = (key: string, defaultValue?: any) => {
      return globalState.user.preferences[key] ?? defaultValue
    }
    
    const hasPermission = (permission: string) => {
      return globalState.user.permissions.includes(permission)
    }
    
    const clearUserState = () => {
      globalState.user.isLoggedIn = false
      globalState.user.userInfo = null
      globalState.user.permissions = []
    }
    
    return {
      isLoggedIn: computed(() => globalState.user.isLoggedIn),
      userInfo: computed(() => globalState.user.userInfo),
      permissions: computed(() => globalState.user.permissions),
      preferences: computed(() => globalState.user.preferences),
      setUserInfo,
      setPermissions,
      setPreference,
      getPreference,
      hasPermission,
      clearUserState
    }
  }
  
  // 测试状态管理
  const useQuizState = () => {
    const setCurrentCategory = (category: string | null) => {
      globalState.quiz.currentCategory = category
    }
    
    const setCurrentQuestionIndex = (index: number) => {
      globalState.quiz.currentQuestionIndex = index
    }
    
    const setAnswer = (questionId: string, answer: any) => {
      globalState.quiz.answers[questionId] = answer
    }
    
    const getAnswer = (questionId: string) => {
      return globalState.quiz.answers[questionId]
    }
    
    const setTimeRemaining = (time: number) => {
      globalState.quiz.timeRemaining = time
    }
    
    const setSubmitting = (submitting: boolean) => {
      globalState.quiz.isSubmitting = submitting
    }
    
    const clearQuizState = () => {
      globalState.quiz.currentCategory = null
      globalState.quiz.currentQuestionIndex = 0
      globalState.quiz.answers = {}
      globalState.quiz.timeRemaining = 0
      globalState.quiz.isSubmitting = false
    }
    
    const getProgress = () => {
      const totalAnswers = Object.keys(globalState.quiz.answers).length
      return totalAnswers
    }
    
    return {
      currentCategory: computed(() => globalState.quiz.currentCategory),
      currentQuestionIndex: computed(() => globalState.quiz.currentQuestionIndex),
      answers: computed(() => globalState.quiz.answers),
      timeRemaining: computed(() => globalState.quiz.timeRemaining),
      isSubmitting: computed(() => globalState.quiz.isSubmitting),
      setCurrentCategory,
      setCurrentQuestionIndex,
      setAnswer,
      getAnswer,
      setTimeRemaining,
      setSubmitting,
      clearQuizState,
      getProgress
    }
  }
  
  // 缓存状态管理
  const useCacheState = () => {
    const setQuestions = (category: string, questions: any[]) => {
      globalState.cache.questions[category] = questions
    }
    
    const getQuestions = (category: string) => {
      return globalState.cache.questions[category] || []
    }
    
    const setResult = (resultId: string, result: any) => {
      globalState.cache.results[resultId] = result
    }
    
    const getResult = (resultId: string) => {
      return globalState.cache.results[resultId]
    }
    
    const setStats = (key: string, stats: any) => {
      globalState.cache.stats[key] = stats
    }
    
    const getStats = (key: string) => {
      return globalState.cache.stats[key]
    }
    
    const clearCache = (type?: 'questions' | 'results' | 'stats') => {
      if (type) {
        globalState.cache[type] = {}
      } else {
        globalState.cache.questions = {}
        globalState.cache.results = {}
        globalState.cache.stats = {}
      }
    }
    
    return {
      questions: computed(() => globalState.cache.questions),
      results: computed(() => globalState.cache.results),
      stats: computed(() => globalState.cache.stats),
      setQuestions,
      getQuestions,
      setResult,
      getResult,
      setStats,
      getStats,
      clearCache
    }
  }
  
  // 状态持久化
  const persistState = () => {
    if (process.client) {
      try {
        const persistData: Record<string, any> = {}
        
        PERSIST_KEYS.forEach(key => {
          const keys = key.split('.')
          let value = globalState as any
          
          for (const k of keys) {
            value = value?.[k]
          }
          
          if (value !== undefined) {
            persistData[key] = value
          }
        })
        
        localStorage.setItem(STORAGE_KEY, JSON.stringify(persistData))
      } catch (error) {
        console.error('状态持久化失败:', error)
      }
    }
  }
  
  // 恢复状态
  const restoreState = () => {
    if (process.client) {
      try {
        const savedData = localStorage.getItem(STORAGE_KEY)
        if (savedData) {
          const persistData = JSON.parse(savedData)
          
          Object.keys(persistData).forEach(key => {
            const keys = key.split('.')
            let target = globalState as any
            
            for (let i = 0; i < keys.length - 1; i++) {
              if (target && keys[i]) {
                target = target[keys[i] as string]
              }
            }
            
            const lastKey = keys[keys.length - 1]
            if (target && lastKey) {
              target[lastKey] = persistData[key]
            }
          })
          
          // 应用主题
          if (globalState.app.theme) {
            document.documentElement.setAttribute('data-theme', globalState.app.theme)
          }
        }
      } catch (error) {
        console.error('状态恢复失败:', error)
      }
    }
  }
  
  // 重置所有状态
  const resetState = () => {
    globalState.app.loading = false
    globalState.user.isLoggedIn = false
    globalState.user.userInfo = null
    globalState.user.permissions = []
    globalState.quiz.currentCategory = null
    globalState.quiz.currentQuestionIndex = 0
    globalState.quiz.answers = {}
    globalState.quiz.timeRemaining = 0
    globalState.quiz.isSubmitting = false
    globalState.cache.questions = {}
    globalState.cache.results = {}
    globalState.cache.stats = {}
    
    if (process.client) {
      localStorage.removeItem(STORAGE_KEY)
    }
  }
  
  // 状态调试
  const debugState = () => {
    console.log('Global State:', globalState)
    return globalState
  }
  
  return {
    // 状态访问
    state: globalState,
    getState,
    
    // 子状态管理
    useAppState,
    useUserState,
    useQuizState,
    useCacheState,
    
    // 持久化
    persistState,
    restoreState,
    resetState,
    
    // 调试
    debugState
  }
}

// 全局状态初始化
export const initializeStore = () => {
  const { restoreState } = useStore()
  restoreState()
}

// 导出类型
export type { GlobalState }